<template>
  <!-- 顶部导航栏 -->
  <van-nav-bar :title="title" right-text="清除购物车" left-text="返回" left-arrow @click-left="$router.go(-1)" @click-right="onClickRight"/>
  <!-- 购物车没有商品时 -->
  <van-empty v-if="addcount == 0" description="购物车无内容" />
  <!-- 商品列表 -->
  <div class="content" v-for="item in cartCountArr" :key="item.proid">
    <van-checkbox-group v-model="checkedArr" ref="checkboxGroup" @click="selectoneFn(item)">
      <van-checkbox :name="item.cartid">
        <van-swipe-cell>
          <van-card  :price="item.originprice.toFixed(2)" :desc="item.proname" class="goods-card"
            :thumb="item.img1" />
            <van-stepper v-model="item.num" @change="changeNumFn" :name="item.cartid" min="1" theme="round" button-size="22" integer />
          <template #right>
            <van-button square @click="deleteFn(item.cartid)" text="删除" type="danger" class="delete-button" />
          </template>
        </van-swipe-cell>
      </van-checkbox>
    </van-checkbox-group>
  </div>
  <van-button class="buy" type="danger" round to="/home">立即购物</van-button>
  <!-- 推荐列表 -->
  <van-cell-group title="可能你还想要"></van-cell-group>
  <van-grid class="list" to="" :border="false" :column-num="2">
    <van-grid-item @click="gotoDetailFn(item.proid)" v-for="item in recommendArr" :key="item.proid">
      <van-image :src="item.img1" />
      <p>{{ item.proname }}</p>
      <span>￥{{ item.originprice }}</span>
    </van-grid-item>
  </van-grid>
  <van-submit-bar :price="totalprice*100" button-text="去结算" @submit="onSubmit">
    <van-checkbox @click="selectallFn" v-model="checkedAll">全选</van-checkbox>
    <template #tip>
      你的收货地址不支持配送, <span @click="$router.push('/address')">修改地址</span>
    </template>
  </van-submit-bar>

</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
// 引入函数形式的组件
import { Toast } from 'vant'
// 引入购物车页面的接口
import { cartlist, recommendlist, removeone, selectall, selectone ,updatenum,removeall} from '@/api/cartapi'
// 引入用户数据管理仓库
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
const router = useRouter()
let count = ref<string>('1')     // 推荐商品的当前页码
// 数组每一项类型定义
interface itemType {
  [propName: string]: any
}
let recommendArr = ref<itemType[]>([])    // 推荐商品数组
const title = ref<string>('')             // 购物车标题
let cartCountArr = ref<itemType[]>([])    // 购物车商品数组
const addcount = ref<number>(0)           // 购物车商品数量
const checked = ref<boolean>(false)       // 单个商品选中状态
const checkedArr = ref<string[]>([])      // 勾选的商品的cartid组成的数组
const checkedAllArr=ref<itemType[]>([])   // 勾选的商品组成的数组
// 选中的商品价格总和
let totalprice = computed<any>(()=>{
  let price=ref<number>(0)
  checkedAllArr.value.forEach((item)=>{
    price.value+=item.num*item.originprice
  })
  return price.value
})
// 定义用户管理仓库的实例
const userStore = useUserStore()
const checkedAll = ref<boolean>(false)
// 定义调用查看购物车的接口的方法
const getcartdata = () => {
  cartlist({ userid: userStore.userId }).then((res: any) => {
    if (res.code == 200) {
      console.log('查看购物车', res);
      addcount.value = res.data.length
      title.value = `购物车(${res.data.length})`
      cartCountArr.value = res.data
      checkedArr.value = cartCountArr.value.filter((item) => {
        return item.flag == true
      }).map((item1) => { return item1.cartid })
      if (checkedArr.value.length == cartCountArr.value.length) {
        checkedAll.value = true
      } else {
        checkedAll.value = false
      }
      checkedAllArr.value = cartCountArr.value.filter((item) => {
        return item.flag == true
      }).map((item1) =>item1 )
    }
  })
}
getcartdata()  // 初始查看购物车数据

// 点击单选按钮
const selectoneFn = (item: any) => {
  // console.log(item.cartid);
  // console.log(checkedArr.value);

  // 01：判断数组中是否包含这一项
  checked.value = checkedArr.value.some((item1) => {
    return item.cartid == item1
  })
  // console.log('单个', checked.value);:
  // 02：调用更新当前购物车数据选中状态的接口
  selectone({ cartid: item.cartid, flag: checked.value }).then((res: any) => {
    console.log('更新当前数据选中状态', res);
    if (res.code == 200) {
      // 03：重新查看购物车数据
      getcartdata()
      // 04：更新全选按钮状态
      console.log(checkedArr.value);
      if (checkedArr.value.length == cartCountArr.value.length && checkedArr.value.length != 0) {
        checkedAll.value = true
      } else {
        checkedAll.value = false
      }
    }
  })
}
// 定义更新购物车所有数据选中状态的接口的方法--所有的
const selectallFn = () => {
  console.log('全选', checkedAll.value);
  if (checkedAll.value) {
    checkedArr.value = cartCountArr.value.map((item => {
      return item.cartid
    }))
  } else {
    checkedArr.value = []
  }
  // 调用更新购物车所有数据选中状态的接口??????????
  // selectall({ userid: userStore.userId, type: checkedAll.value }).then((res: any) => {
  //   console.log('更新所有数据选中状态', res);
  //   if (res.code == 200) {
  //   }
  // })
  // getcartdata()  // 重新查看购物车数据
}
// 商品数量发生变化时
const changeNumFn=(value:number,details:{name:string})=>{
  console.log(value,details.name);
  // 调用更新商品数量的接口
  updatenum({cartid:details.name,num:value}).then((res:any)=>{
    if(res.code==200){
      console.log('更新商品数量',res);
    }
  })
}

// 调用推荐商品的列表
recommendlist({ count: count.value, limitNum: '12' }).then((res: any) => {
  if (res.code == 200) {
    console.log('推荐商品列表', res);
    recommendArr.value = res.data
  }
})
// 删除单个数据
const deleteFn = (cartid: string) => {
  // console.log(cartid);
  // 调用删除单个数据
  removeone({ cartid: cartid }).then((res: any) => {
    if (res.code == 200) {
      // console.log('删除单条数据',res);
      // 重新查看购物车数据
      getcartdata()
    }
  })
}
// 点击清除购物车
const onClickRight=()=>{
  removeall({userid:userStore.userId}).then((res:any)=>{
    if(res.code==200){
       // 重新查看购物车数据
       getcartdata()
    }
  })
}
// 点击去结算按钮
const onSubmit = () => Toast('进入支付页面');
// 点击推荐商品跳转到商品详情页面
const gotoDetailFn = (id: string) => {
  console.log(id);
  router.push({ path: `/details/${id}` })

}
</script>
<style lang="scss" scoped>
.buy {
  margin: 20px 140px 0;
}

.list {
  p {
    width: 165.5px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    font-size: 13px;
  }

  span {
    color: #ee0a24;
    margin-left: -110px;
    font-weight: 600;
  }
}

.van-cell-group__title {
  text-indent: 100px;
  padding: 100px;
  margin: 100px;
  background-color: pink;
  height: 100px;
}

.goods-card {
  margin: 0;
  background-color: #fff;
}

.delete-button {
  height: 100%;
}

.van-swipe-cell {
  margin-top: 10px;
  position: relative;
  .van-stepper{
    position: absolute;
    top: 70px;
    left: 240px;
  }
}

::v-deep .van-swipe-cell__wrapper {
  transform: translate3d(-47.6px, 0px, 0px)
}

::v-deep .van-card__desc {
  margin-top: 10px;
  font-size: 16px;
}

.content {
  padding-left: 10px;
  
}

.van-card {
  width: 330px;
  
}
</style>